package com.example.budget3.modify;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import com.example.budget3.R;
import com.example.budget3.data.ExpenseCategory;
import com.example.budget3.data.IncomeCategory;
import com.example.budget3.data.TransactionData;
import com.example.budget3.util.TransactionDataContract;
import com.example.budget3.util.UtilMethods;
import com.example.budget3.util.TransactionDataContract.DataEntry;
import com.example.budget3.util.TransactionDataContract.TransactionDataDbHelper;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

public class EditTransaction extends AddTransaction {

	private int entryId;
	

	public static final String ENTRY_ID = "entryId";

	public void onCreate(Bundle savedInstanceState) {
		

		Bundle extras = getIntent().getExtras();
		entryId = extras.getInt(ENTRY_ID);
		TransactionData data = loadData(entryId);

		
        if(savedInstanceState == null){
        	Bundle newSavedInstanceState  = new Bundle();
        	
        	
        	Calendar calendar = Calendar.getInstance();
			calendar.setTime(data.getTimeDate());
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH);
			int day = calendar.get(Calendar.DAY_OF_MONTH); 
			int hour = calendar.get(Calendar.HOUR_OF_DAY);
			int minute = calendar.get(Calendar.MINUTE);
			boolean expense = data.isExpenseType();
	        int insel = 0;
	        int outsel = 0;
	        if(expense){
	        	outsel = data.getExpenseCategory().ordinal() +1;
	        }else{
	        	insel = data.getIncomeCategory().ordinal() +1;
	        }

        	newSavedInstanceState.putBoolean("expense", data.isExpenseType());
        	newSavedInstanceState.putBoolean("recurring", false);
        	newSavedInstanceState.putInt("insel", insel);
        	newSavedInstanceState.putInt("outsel", outsel);
        	newSavedInstanceState.putInt("minute", minute);
        	newSavedInstanceState.putInt("hour", hour);
        	newSavedInstanceState.putInt("day", day);
        	newSavedInstanceState.putInt("rechour", 0);
			newSavedInstanceState.putInt("recminute", 0);
			newSavedInstanceState.putInt("month", month);
			newSavedInstanceState.putInt("year", year);
			newSavedInstanceState.putInt("spinnerPos", 0);
			newSavedInstanceState.putBoolean("includeTimeToday", false);
			newSavedInstanceState.putBoolean("includeWeekToday", false);
			newSavedInstanceState.putBoolean("includeMonthToday", false);
			newSavedInstanceState.putInt("dayOfWeek", 0);
			newSavedInstanceState.putInt("dayOfMonth", 0);
			newSavedInstanceState.putString("name", data.getName());
			newSavedInstanceState.putString("text", UtilMethods.getCostToString(this, data.getCost()));
			newSavedInstanceState.putBoolean("first", false);
			super.onCreate(newSavedInstanceState);
			

        }else{
        	super.onCreate(savedInstanceState);
        }
        
		recurButton.setVisibility(View.GONE);
		singleButton.setVisibility(View.GONE);

 
	}
	
	

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_save:

        	if(checkFields()){
        		store2();
        		Intent result = new Intent();
        	    result.putExtra("updated", true);
        		setResult(RESULT_OK, result);
	        	finish();
	        	return true;
        	}
   
            return false;
         // Respond to the action bar's Up/Home button
	    case android.R.id.home:
	    	finish();
	    	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

	private void store2() {
		TransactionDataContract contract = new TransactionDataContract();
		TransactionDataDbHelper mDbHelper = contract.new TransactionDataDbHelper(getApplicationContext());
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
	
		values.put(DataEntry.COLUMN_NAME_NAME, getName());
		values.put(DataEntry.COLUMN_NAME_COST, getCost());
		values.put(DataEntry.COLUMN_NAME_CATEGORY, getCatagory());
		values.put(DataEntry.COLUMN_NAME_TIME, getTime());
		values.put(DataEntry.COLUMN_NAME_TYPE, isExpense());
		
		
		
		values.put(DataEntry._ID, entryId);
		
		// Insert the new row, returning the primary key value of the new row
		db.replace(DataEntry.TABLE_NAME,
				  DataEntry.COLUMN_NAME_NULLABLE,
		          values);

	}




	private TransactionData loadData(int entryId) {
		TransactionDataContract contract = new TransactionDataContract();
		TransactionDataDbHelper mDbHelper = contract.new TransactionDataDbHelper(this);
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		
		// Define a projection that specifies which columns from the database
		// you will actually use after this query.

		String[] selectionArgs = new String[0];
		String sql = "SELECT * from "+DataEntry.TABLE_NAME+" where "+DataEntry._ID+" == "+ entryId;
		Cursor mycursor = db.rawQuery(sql, selectionArgs);
		
	
		
		if (mycursor.moveToFirst())
		{     
    		String name = mycursor.getString(
    				mycursor.getColumnIndexOrThrow(DataEntry.COLUMN_NAME_NAME));
    		float cost = mycursor.getFloat(
    				mycursor.getColumnIndexOrThrow(DataEntry.COLUMN_NAME_COST));
    		int catOrd = mycursor.getInt(
    				mycursor.getColumnIndexOrThrow(DataEntry.COLUMN_NAME_CATEGORY));
    		
    		
    		String time = mycursor.getString(
    				mycursor.getColumnIndexOrThrow(DataEntry.COLUMN_NAME_TIME));
    		int id = mycursor.getInt(
    				mycursor.getColumnIndexOrThrow(DataEntry._ID));
    		
    		Date timeDate;
			try {
				timeDate = UtilMethods.stringToDate(time);
				boolean type = mycursor.getInt(
    				mycursor.getColumnIndexOrThrow(DataEntry.COLUMN_NAME_TYPE)) == 0 ? false:true;
				if(type){
					ExpenseCategory category = ExpenseCategory.values()[catOrd];
					return new TransactionData(id, name, cost, category, timeDate, type);
				}else{
					IncomeCategory category = IncomeCategory.values()[catOrd];
					return new TransactionData(id, name, cost, category, timeDate, type);
				}
				
				
			} catch (ParseException e) {
			}
		}
		return null;
			
	}
	
	
}
